package br.ufc.apsoo.validators;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import com.google.common.base.Strings;

public class CPFValidator implements ConstraintValidator<CPF, String> {

	private CPF anotacao;

	@Override
	public void initialize(CPF anotacao) {
		this.anotacao = anotacao;
	}

	@Override
	public boolean isValid(String cpfNum, ConstraintValidatorContext context) {
		if (Strings.isNullOrEmpty(cpfNum)) {
			return true;
		}
			
		int resultP = 0;
		int resultS = 0;
		
		String cpfSemMascara = cpfNum.replaceAll("[.]", "").replace("-", "");
		int[] cpf = new int[cpfSemMascara.length()];
		
		if (cpfSemMascara.length() != 11) {
			return false;
		}

		for (int i = 0; i < cpf.length; i++) {
			cpf[i] = Integer.parseInt(cpfSemMascara.substring(i, i + 1));
		}

		for (int i = 0; i < 9; i++) {
			resultP += cpf[i] * (i + 1);
		}

		int divP = resultP % 11;

		if (divP != cpf[9]) {
			return false;
		} else {
			for (int i = 0; i < 10; i++) {
				resultS += cpf[i] * (i);
			}

			int divS = resultS % 11;

			if (divS != cpf[10]) {
				return false;
			}
		}

		return true;
	}

}
